package com.sunni.controller;

import com.sunni.entity.Admin;
import com.sunni.service.BookService;
import com.sunni.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
    BookService bookService = new BookServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       Integer page =  req.getParameter("page") == null ? 1 : Integer.parseInt(req.getParameter("page"));
       String method = req.getParameter("method") == null ? "findAllByState0" : req.getParameter("method");
        Integer state =  req.getParameter("state") == null ? 0 : Integer.parseInt(req.getParameter("state"));

       switch (method){
           case "findAllByState0":
               req.setAttribute("borrowListByState0",bookService.findAllByState0(0,page));
               req.setAttribute("everyPageProject",6);
               req.setAttribute("nowPage",page);
               req.setAttribute("pageTotal",bookService.getPageCountBorrowByState0(0));
               req.getRequestDispatcher("admin.jsp").forward(req,resp);
               break;
           case "handle":
               HttpSession session = req.getSession();
               Admin admin = (Admin) session.getAttribute("admin");
               Integer adminId = admin.getId();
               Integer borrowId = null;
               try {
                   borrowId =  Integer.parseInt(req.getParameter("borrowId"));
               } catch (NumberFormatException e) {
                   System.out.println(e);
               }
              Integer handleResult =  bookService.handleByBorrowid(borrowId,state,adminId);
               if (handleResult == null || handleResult <=0 ){
                    resp.setContentType("text/html;charset=UTF-8");
                    resp.getWriter().write("操作失败，请重试。");
                }else {
                    resp.sendRedirect("/admin");
                }


               break;
       }
    }
}
